package com.empty_pro.newone;

import androidx.activity.result.ActivityResult;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Telephony;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

public class RateListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener,Runnable {
    private Handler handler;
    private ProgressBar bar;
    ArrayAdapter adapter;
    ListView gridView;

    String mYear,mMonth,mDay,year,month,day;
    private static final String TAG = "ratelist";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_rate_list);
        gridView = findViewById(R.id.gridview);
        bar = findViewById(R.id.bar);

        gridView.setOnItemLongClickListener(this);
        gridView.setOnItemClickListener(this);

        //

        //获取sp中保存的数据
        SharedPreferences share = getSharedPreferences("date", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);
        year= share.getString("year","wrong");
        day= share.getString("day","wrong");
        month= share.getString("month","wrong");
        //

        //获取年月日信息
        Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        mYear = String.valueOf(c.get(Calendar.YEAR)); // 获取当前年份
        mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
        mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码





        handler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 5) {
                    List<String> list2 = (List<String>) msg.obj;
                    adapter = new ArrayAdapter<String>(RateListActivity.this,
                            android.R.layout.simple_list_item_1, list2);

                    gridView.setAdapter(adapter);
                    gridView.setEmptyView(bar);
                }
                super.handleMessage(msg);
            }
        };

        /*
        MyNetWork1 rask = new MyNetWork1();
        rask.setHandler(handler);




         */


        Thread t = new Thread();
        t.start();




    }

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int pos, long id) { 
        //adapter.remove(gridView.getItemAtPosition(pos));

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示")
                .setMessage("请确认是否删除当前数据")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        adapter.remove(gridView.getItemAtPosition(pos));
                    }
                }).setNegativeButton("否",null);
        builder.create().show();
        return true;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Log.i(TAG, "onItemClick: position" + i);
    }

    @Override
    public void run() {

        Log.i("List","run...");
        List<String> retList = new ArrayList<String>();
        Message msg = handler.obtainMessage();
        if(year.equals(mYear) && day.equals(mDay) && month.equals(mMonth)){
            //如果相等，则不从网络中获取数据
            Log.i("run","日期相等，从数据库中获取数据");
            RateManager dbManager = new RateManager(RateListActivity.this);
            for(RateItem rateItem : dbManager.listAll()){
                retList.add(rateItem.getCurName() + "=>" + rateItem.getCurRate());
            }
        }else{
            Log.i("run","日期不等，从网络中获取在线数据");
            //获取网络数据
            List<RateItem> rateList = new ArrayList<RateItem>();
            String url = "https://www.boc.cn/sourcedb/whpj/";
            try {
                Document doc = Jsoup.connect(url).get();

                String html= doc.html();
                //Log.i(TAG, "run: 解析结果日志输出"+html);

                Element table = doc.getElementsByTag("table").get(1);
                Elements tds = table.getElementsByTag("td");

                for (int i = 0; i < tds.size(); i += 8) {
                    Element td1 = tds.get(i);
                    Element td2 = tds.get(i + 5);

                    float val = Float.parseFloat(td2.text());
                    val = 100/val;
                    retList.add(td1.text() + "->" + val);

                    RateItem rateItem = new RateItem(td1.text(),td2.text());
                    rateList.add(rateItem);
                }

                RateManager dbManager = new RateManager(RateListActivity.this);
                dbManager.deleteAll();
                Log.i("db","删除所有记录");
                dbManager.addAll(rateList);
                Log.i("db","添加新记录集");

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            //更新记录日期
            SharedPreferences sp = getSharedPreferences("date", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("year", mYear);
            editor.putString("month", mMonth);
            editor.putString("day", mDay);


        }

        msg.obj = retList;
        msg.what = 5;
        handler.sendMessage(msg);
    }


}